package com.thread.lianxi;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

public class ProducerAndConsumer {

	static int count = 0;

	public static void main(String[] args) {

		System.out.println("上课了。。。。");
		// 一个可以装10颗糖的罐子
		BlockingQueue<String> candyPot = new LinkedBlockingQueue<String>(10);

		ExecutorService service = Executors.newFixedThreadPool(10);

		// 8个小孩
		for (int i = 0; i < 8; i++) {
			service.execute(new Child("小孩" + i, candyPot));
		}
		// 2个阿姨
		for (int i = 0; i < 2; i++) {
			service.execute(new Aunt("阿姨" + i, candyPot));
		}
		service.shutdown();

	}

	// 小孩
	static class Child implements Runnable {

		BlockingQueue<String> candyPot;
		String name;

		public Child(String name, BlockingQueue<String> candyPot) {
			this.candyPot = candyPot;
			this.name = name;
		}

		@Override
		public void run() {

			while (true) {
				try {
					System.out.println(name + " 等待吃糖");
					long start = (new Date()).getTime();
					String candy = candyPot.take();
					long end = (new Date()).getTime();
					System.out.println(name + " 耗时" + (end - start) + "毫秒把" + candy + "从糖罐拿了出来");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

		}

	}

	// 做糖果的阿姨
	static class Aunt implements Runnable {

		BlockingQueue<String> candyPot;
		String name;

		public Aunt(String name, BlockingQueue<String> candyPot) {
			this.candyPot = candyPot;
			this.name = name;
		}

		static String[] candyType = { "苹果糖", "牛奶糖", "咖啡糖", "玉米糖", "旺仔" };

		@Override
		public void run() {
			while (true) {
				try {
					if (count > 99) {
						System.out.println("今天已经做了100个糖了！下课");
						break;
					}
					System.out.println("==");
					count++;
					Random r = (new Random());
					String candy = candyType[r.nextInt(candyType.length)];
					int sleepTime = r.nextInt(50000);
					System.out.println(name + " 耗时" + sleepTime + "毫秒 做了一个" + candy);
					long start = (new Date()).getTime();
					candyPot.put(candy);
					long end = (new Date()).getTime();
					System.out.println(name + " 耗时" + (end - start) + "毫秒把" + candy + "放进了糖罐");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

	}

}
